import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Radio,
  Upload,
  Space,
  Button,
  message,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Link, useParams } from "react-router-dom";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import styles from "./index.module.scss";
import Channel from "@/components/Channel";
import { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { addArticle, getArticle, editArticle } from "@/store/actions";
import { useHistory } from "react-router-dom";

const Publish = () => {
  // 封面逻辑
  const [type, setType] = useState(1);
  const onTypeChange = (e) => {
    setType(e.target.value);
    // 重置上传图片的数据
    setFileList([]);
  };
  const [fileList, setFileList] = useState([]);
  const onUploadChange = ({ fileList }) => {
    // fileList 上传一张图 [{}]  再上传一张 [{},{}] 是一个新数组
    // 对象中会存储上传成功后的图片途径，将来提交文章数据再去取出来
    setFileList(fileList);
  };

  // 发布逻辑(合并编辑逻辑)
  const dispatch = useDispatch();
  const history = useHistory();
  // form触发onFinish函数，是没有第二个参数，默认不是存入草稿
  const onFinish = async (values, draft = false) => {
    // 提交之前，对封面类型和上传图片张数做校验
    if (type !== fileList.length) {
      return message.warning("上传图片张数和封面类型不一致");
    }
    // 提交之前，组织后台需要的数据
    const data = {
      ...values,
      cover: {
        type,
        // 兼容两种数据格式：[{response:{data:{url:'图片地址'}}}]  [{url:'图片地址'}]
        images: fileList.map((item) => item?.response?.data?.url || item.url),
      },
    };
    if (params.id) {
      // 修改提交
      data.id = params.id
      await dispatch(editArticle(data, draft))
    } else {
      // 添加提交
      await dispatch(addArticle(data, draft));
    }
    message.success("保存成功");
    // 跳转内容管理
    history.push("/article");
  };
  // 存入草稿
  const saveArticle = async () => {
    // 1. 对表单进行校验，获取values数据
    // 2. 调用onFinish函数传入values和是否存入草稿
    const values = await form.validateFields()
    onFinish(values, true)
  }


  // 编辑页面显示逻辑
  const params = useParams();
  const [form] = Form.useForm();
  useEffect(() => {
    // 第一次渲染组件完毕
    const initialFormValues = async () => {
      if (params.id) {
        // 回显数据
        const { title, channel_id, content, cover } = await dispatch(
          getArticle(params.id)
        );
        form.setFieldsValue({ title, channel_id, content });
        setType(cover.type);
        // fileList [{},...] 对象中有url就可以显示图片
        setFileList(cover.images.map((item) => ({ url: item })));
      } else {
        // 编辑状态====>发布状态
        // 重置数据
        form.resetFields();
        setType(1);
        setFileList([]);
      }
    };
    initialFormValues();
  }, [dispatch, form, params.id]);

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <Link to="/article">内容管理</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{params.id ? "修改" : "发布"}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form form={form} labelCol={{ span: 4 }} onFinish={onFinish}>
          <Form.Item
            label="文章标题："
            name="title"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="所属频道："
            name="channel_id"
            rules={[{ required: true, message: "请选择所属频道" }]}
          >
            <Channel width={400} />
          </Form.Item>
          <Form.Item label="文章封面：">
            {/* 单选框组 如果以后加上name属性就OK，只能有一个子元素*/}
            <Form.Item style={{ marginBottom: 0 }}>
              <Radio.Group value={type} onChange={onTypeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {/* 上传组件 */}
            {type > 0 && (
              <div style={{ marginTop: 16 }}>
                <Upload
                  action="http://geek.itheima.net/v1_0/upload"
                  listType="picture-card"
                  name="image"
                  fileList={fileList}
                  onPreview={() => {}}
                  onChange={onUploadChange}
                >
                  {fileList.length >= type ? null : (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传图片</div>
                    </div>
                  )}
                </Upload>
              </div>
            )}
          </Form.Item>
          <Form.Item
            label="文章内容："
            wrapperCol={{ span: 16 }}
            name="content"
            initialValue=""
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            {/* 设置name之后，给ReactQuill赋值，只能是字符串数据 initialValue="" */}
            <ReactQuill />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {params.id ? "修改" : "发布"}文章
              </Button>
              <Button onClick={saveArticle}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
